import React from 'react';
import Api from 'Utils/api';
import { Form, Input, message, Button, Icon, Radio } from 'antd';
import { connect } from 'react-redux';
import { API_HOST } from 'Constants/config';
import * as routerActions from 'react-router-redux';
import FILES_TYPE from 'Constants/ShiAnConstants';
import VR_TYPE from 'Constants/vrType';
import PicturesWall from '../../../../../UploadImage';
import CommonBorder from './../../../../DispatchPage/Components/CommonBorder';

const { TextArea } = Input;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
class AddPage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isAdd: false,
      id: props.params.id,
      editRecord: '',
      mediaType: '',
      loading: false,
      isLink: true,
      initialValue: ''
    };
    this.onEnter = ::this.onEnter;
    this.initForm = ::this.initForm;
    this.returnVrType = ::this.returnVrType;
    this.insertVrInfos = ::this.insertVrInfos;
  }
  componentDidMount() {
    this.initForm();
    const { id } = this.state;
    if (!id) {
      document.getElementById('close').style.display = 'none';
    }
  }
  componentWillMount() {
    const { id } = this.state;
    if (!id) {
      this.setState({ isAdd: true });
    }
  }
  initForm() {
    const { id } = this.state;
    if (id) {
      const api = new Api({
        method: 'GET',
        path: `/documents/${id}`,
        success: (json) => {
          this.setState({ editRecord: json, mediaType: json.media_type, isLink: !!json.vr_link });
          if (json.media) {
            this.insertVrInfos(json.media_type, json.media);
          }
          if (!json.media && document.getElementById('close')) {
            document.getElementById('close').style.display = 'none';
          }
        }
      });
      api.run();
    }
  }
  insertVrInfos(mediaType, media) {
    if (this.returnVrType(mediaType) === VR_TYPE.video) {
      if (!this.vrVideo) {
        this.vrVideo = new VRView.Player('#video', {
          width: '100%',
          height: '300',
          video: `${API_HOST}/files/${media}`,
          is_stereo: false,  //区分是mono还是stereo
        });
      } else {
        this.vrVideo.setContent({
          video: `${API_HOST}/files/${media}`,
        });
      }
    }
    if (this.returnVrType(mediaType) === VR_TYPE.img) {
      if (!this.vrVideo) {
        this.vrVideo = new VRView.Player('#video', {
          width: '100%',
          height: '300',
          image: `${API_HOST}/files/${media}`,
          is_stereo: false,  //区分是mono还是stereo
        });
      } else {
        this.vrVideo.setContent({
          image: `${API_HOST}/files/${media}`,
        });
      }
    }
  }
  onEnter() {
    const { id, mediaType, isLink } = this.state;
    const formValue = this.props.form.getFieldsValue();
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        if (!isLink && !mediaType) {
          message.error('请上传vr格式的视频或图片');
          return;
        }
        const { title, vr_link, thumbnail_id, content } = formValue;
        let data = {};
        if (isLink) {
          data = {
            title,
            vr_link,
            thumbnail_id,
            content: '',
            media: 0
          };
        } else {
          data = {
            title,
            media: this.state.type,
            content,
            vr_link: '',
            thumbnail_id: 0
          };
        }
        if (id) {
          this.setState({ loading: true });
          const editApi = new Api({
            method: 'PATCH',
            path: `/documents/admin/${id}`,
            data: {
              ...data,
              media_type: isLink ? 'image' : this.state.mediaType
            },
            success: () => {
              this.setState({ loading: false });
              this.props.dispatch(routerActions.goBack());
            },
            error: () => {
              this.setState({ loading: false });
            }
          });
          editApi.run();
        } else {
          this.setState({ loading: true });
          const addApi = new Api({
            method: 'POST',
            path: `/documents/admin/${FILES_TYPE.vr}`,
            data: {
              ...data,
              media_type: isLink ? 'image' : this.state.mediaType
            },
            success: () => {
              this.setState({ loading: false });
              this.props.dispatch(routerActions.goBack());
            },
            error: () => {
              this.setState({ loading: false });
            }
          });
          addApi.run();
        }
      }
    });
  }
  returnVrType(type) {
    if (type.indexOf('video') > -1) {
      return VR_TYPE.video;
    }
    if (type.indexOf('image') > -1) {
      return VR_TYPE.img;
    }
    return false;
  }
  uploadVideo() {
    const file = document.getElementById('upload').files[0];
    if (!this.returnVrType(file.type)) {
      message.error('请上传vr格式的视频或图片');
      return;
    }
    const formData = new window.FormData();
    formData.append('upload_file', file, file.name);
    const api = new Api({
      method: 'POST',
      path: '/files',
      noHeader: true,
      data: formData,
      success: (json) => {
        document.getElementById('close').style.display = 'block';
        this.setState({
          type: json.id,
          src: `${API_HOST}/files/${json.id}`,
          mediaType: this.returnVrType(file.type)
        });
        this.insertVrInfos(file.type, json.id);
      },
      error: () => {
      },
    });
    api.run();
  }
  handleDeleteVr() {
    this.props.form.setFieldsValue({ flow_vr: undefined });
    document.getElementById('video').innerHTML = '';
    this.setState({
      mediaType: '',
      type: ''
    });
    this.vrVideo = undefined;
    document.getElementById('close').style.display = 'none';
  }
  linkChange(e) {
    const { mediaType, type, editRecord } = this.state;
    const formValue = this.props.form.getFieldsValue();
    this.setState({
      isLink: e.target.value,
      editRecord: Object.assign({}, { ...editRecord }, { ...formValue }, { media: this.state.editRecord.media })
    }, () => {
      if (!this.state.isLink && mediaType && (type || this.state.editRecord.media)) {
        this.vrVideo = undefined;
        if (type) {
          this.insertVrInfos(mediaType, type);
        } else {
          this.insertVrInfos(mediaType, this.state.editRecord.media);
        }
        document.getElementById('close').style.display = 'block';
      } else if (document.getElementById('close')) {
        document.getElementById('close').style.display = 'none';
      }
    });
  }
  render() {
    const title = this.state.isAdd ? '新增' : '修改';
    const { form } = this.props;
    const initialValue = this.state.editRecord;
    const { getFieldDecorator } = form;
    return (
      <CommonBorder
        title={`VR虚拟现实${title}`}
        content={
          <div className="dynamic-content">
            <Form layout={'horizontal'} className="report-form add-vr-page" >
              <FormItem label="标题" >
                {getFieldDecorator('title', {
                  initialValue: initialValue ? initialValue.title : '',
                  rules: [
                    { required: true, message: '请输入标题' }
                  ]
                })(
                  <Input placeholder="请输入标题" style={{ width: 840 }} />
                )}
              </FormItem >
              <FormItem label="外部链接">
                <RadioGroup onChange={this.linkChange.bind(this)} value={this.state.isLink}>
                  <Radio value>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>
              </FormItem>
              {
                this.state.isLink ?
                  <div>
                    <FormItem label="链接地址" >
                      {getFieldDecorator('vr_link', {
                        initialValue: initialValue ? initialValue.vr_link : '',
                        rules: [
                          { required: true, message: '请输入地址' }
                        ]
                      })(
                        <Input placeholder="请输入完整外部链接地址" style={{ width: 840 }} />
                      )}
                    </FormItem >
                    <FormItem label="封面" >
                      {getFieldDecorator('thumbnail_id', {
                        initialValue: initialValue && initialValue.thumbnail_id ? initialValue.thumbnail_id : '',
                        rules: [
                          { required: true, message: '请上传封面' }
                        ]
                      })(
                        <PicturesWall
                          initImg={initialValue.thumbnail_id ? [initialValue.thumbnail_id] : []}
                          isOpen={initialValue.thumbnail_id !== undefined}
                        />
                      )}
                    </FormItem >
                  </div>
                  :
                  <div>
                    <FormItem label="VR" >
                      {getFieldDecorator('media', {
                      })(
                        <div style={{ width: 840, textAlign: 'left' }} className="opreate-vr-wrap">
                          <input type="file" accept="video/*,image/*" id="upload" onChange={this.uploadVideo.bind(this)} />
                          <img src="images/dispatch/icon_add.png" alt="添加" />
                          <div id="video">{''}</div>
                          <Icon id="close" type="close-circle-o" className="vr-close" onClick={this.handleDeleteVr.bind(this)} />
                        </div>
                      )}
                    </FormItem >
                    <FormItem label="内容" >
                      {getFieldDecorator('content', {
                        initialValue: initialValue ? initialValue.content : '',
                        rules: [
                          { required: true, message: '请输入内容' }
                        ]
                      })(
                        <TextArea placeholder="请输入内容" rows={4} style={{ width: 840, height: 300 }} />
                      )}
                    </FormItem >
                  </div>
              }
            </Form >
            <div className="b-wrap">
              <Button className="ok-btn" onClick={this.onEnter.bind(this)} loading={this.state.loading}>
                <img src="images/dispatch/icon_public.png" alt="" />
                <span>发布</span >
              </Button>
            </div>
          </div>
        }
      />
    );
  }
}


function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}

export default Form.create()(connect(mapStateToProps)(AddPage));
